using System.Diagnostics;
using IniParser;
using IniParser.Model;
using MySql.Data.MySqlClient;
using SevenZip;
using 打包工具.Properties;

namespace 打包工具
{
    public partial class Form1 : Form
    {
        private const string Chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        private const string Code = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        private static readonly Random Random = new();
        private static string _modPath = "";

        public Form1()
        {
            InitializeComponent();
        }

        private static void UpLoadModInfo(string modName, string modUnlockCode, string modPassword)
        {
            // 数据库连接字符串
            const string connectionString =
                "Server=101.132.40.214;Port=3306;Database=spirithun;Uid=spirithun;Pwd=euU9EgTWW8uOMt8m;";
            MySqlConnection connection = new(connectionString);
            try
            {
                connection.Open(); // 尝试打开数据库连接
                Console.WriteLine("Database connection successful!");
                // 构造插入数据的SQL命令
                var command =
                    new MySqlCommand(
                        $"INSERT INTO mod_list (mod_name, mod_unlock_code,mod_unzip_password,unlock_code_status) VALUES ('{modName}', '{modUnlockCode}', '{modPassword}',0)",
                        connection);
                if (command.ExecuteNonQuery() != -1)
                {
                    connection.Close();
                }
                else
                {
                    MessageBox.Show("上传失败，请重试！", "Mod管家 - 打包工具", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
            catch (Exception e)
            {
                // 捕获异常，显示错误信息，并退出应用程序
                MessageBox.Show($"软件初始化错误！错误信息: {e.Message}", "Mod管家 - 打包工具", MessageBoxButtons.OK,
                    MessageBoxIcon.Error);
                Application.Exit();
            }
        }


        private static string GeneratePassword(int length)
        {
            char[] password = new char[length];
            for (int i = 0; i < length; i++)
            {
                password[i] = Chars[Random.Next(Chars.Length)];
            }

            return new string(password);
        }

        private static string GenerateCode(int length)
        {
            int codeLength = 16;
            if (length != 0)
            {
                codeLength = length;
            }

            char[] code = new char[codeLength];
            for (int i = 0; i < codeLength; i++)
            {
                code[i] = Code[Random.Next(Code.Length)];
            }
            Console.WriteLine(new string(code));
            return new string(code);
        }

        private void CustomSuffix_Click(object sender, EventArgs e)
        {
            if (CustomSuffix.Checked)
            {
                MessageBox.Show("选中本选项时，会生成配置文件，需将配置文件放在MOD工具文件夹内，才可以识别自定义后缀的mod！", "提示", MessageBoxButtons.OK,
                    MessageBoxIcon.Information);
                Suffix.Enabled = true;
            }
            else
            {
                Suffix.Enabled = false;
                Suffix.Text = ".7z";
            }


        }

        private void RandomPwd_Click(object sender, EventArgs e)
        {
            ModPwd.Text = GeneratePassword(16);
        }

        private void SelectModDirectory_Click(object sender, EventArgs e)
        {
            var result = OpenModFolder.ShowDialog();
            if (result == DialogResult.OK)
            {
                _modPath = OpenModFolder.SelectedPath;
                Console.WriteLine($"已选择 MOD 文件夹：{_modPath}");
                SelectModDirectory.Text = "已选择";
                SelectModDirectory.Enabled = false;
                StartPack.Enabled = true;
            }
            else
            {
                MessageBox.Show("请选择MOD文件夹", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private async void StartPack_Click(object sender, EventArgs e)
        {
            if (ModName.Text == "")
            {
                MessageBox.Show("请输入MOD名称", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (ModPwd.Text == "")
            {
                MessageBox.Show("请输入MOD密码", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (Suffix.Text == "")
            {
                MessageBox.Show("请输入MOD后缀", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            string modCode = GenerateCode(UnLockCodeLength.Text == "" ? 0 : int.Parse(UnLockCodeLength.Text));

            // 获取当前应用程序域的基础目录
            string basePath = AppDomain.CurrentDomain.BaseDirectory;
            // 拼接7z.dll文件的路径
            string libPath = Path.Combine(basePath, Environment.Is64BitOperatingSystem ? "x64" : "x86", "7z.dll");
            // 设置7-Zip库的路径
            SevenZipBase.SetLibraryPath(libPath);
            var compressor = new SevenZipCompressor
            {
                ArchiveFormat = OutArchiveFormat.SevenZip,
                CompressionMode = CompressionMode.Create,
                CompressionLevel = CompressionLevel.High,
                DirectoryStructure = true,
                ZipEncryptionMethod = ZipEncryptionMethod.Aes256,
                EncryptHeaders = true // 加密文件名
            };
            compressor.Compressing += Compressor_Compressing!;
            SaveModPack.FileName = ModName.Text;
            SaveModPack.Filter = $"Mod管家 MOD包文件|*{Suffix.Text}";
            SaveModPack.Title = "选择MOD包保存位置";
            var modPath = SaveModPack.ShowDialog();
            if (modPath != DialogResult.OK) return;
            try
            {
                string directoryToCompress = _modPath;
                string compressedFileName = SaveModPack.FileName;
                string password = ModPwd.Text;
                await Task.Run(() =>
                {
                    compressor.CompressDirectory(directoryToCompress, compressedFileName, password);
                }).ConfigureAwait(true);
                if (CustomSuffix.Checked)
                {
                    var parser = new FileIniDataParser();
                    var data = File.Exists(Path.Combine(basePath, "AppConfig.ini"))
                        ? parser.ReadFile(Path.Combine(basePath, "AppConfig.ini"))
                        : new IniData();
                    data["AppConfig"]["Suffix"] = Suffix.Text;
                    parser.WriteFile(Path.Combine(basePath, "AppConfig.ini"), data);
                    MessageBox.Show("已生成配置文件，请将配置文件AppConfig.ini放在MOD工具文件夹内，才可以识别自定义后缀的mod！", "提示",
                        MessageBoxButtons.OK, MessageBoxIcon.Information);
                }

                UpLoadModInfo(ModName.Text, modCode, password);
                MessageBox.Show("Mod打包完成!!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Invoke(() =>
                {
                    SelectModDirectory.Enabled = true;
                    SelectModDirectory.Text = "选择Mod文件夹";
                    StartPack.Enabled = false;
                });
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }

        private void Suffix_Leave(object sender, EventArgs e)
        {
            if (sender is TextBox { Text.Length: > 0 } textBox && !textBox.Text.StartsWith("."))
            {
                textBox.Text = "." + textBox.Text;
            }
        }

        private void Compressor_Compressing(object sender, PercentDoneEventArgs e)
        {
            Invoke(() =>
            {
                progressBar1.Value = e.PercentDone;
            });
        }

        private void DemoImg_Click(object sender, EventArgs e)
        {
            var imgDemo = new ImgDemo();
            imgDemo.ShowDialog();
        }

        private void DemoFile_Click(object sender, EventArgs e)
        {
            byte[]? demo = Resources.Demo;
            string path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Demo.7z");
            using (var fs = new FileStream(path,FileMode.Create))
            {
                fs.Write(demo, 0, demo.Length);
            }
            
            Console.WriteLine(path);
            try
            {
                var psi = new ProcessStartInfo(path)
                {
                    UseShellExecute = true
                };
                    Process.Start(psi);
            }
            catch (Exception ex)
            {
                MessageBox.Show($"无法打开文件：{ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}